#include "stdafx.h"
#include "TemplateWindow.h"

#include <metaioSDK/IMetaioSDK.h>
#include <QtWidgets/QApplication>
#include "AppConfig.h"
#include "CmdResult.h"

#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")

IInsTcpClient* TcpClient = nullptr;

int main(int argc, char *argv[])
{
	try
	{
		CmdResult result;
		do
		{
			if (InitInsNetwork())
			{
				TcpClient = IInsTcpClient::CreateIns();
				if (!TcpClient || !TcpClient->Open(&result))
				{
					qCritical("Create local TCP client failed.");
					break;
				}

				if (!TcpClient->Connect(AppConfig::instance()->ip.c_str(), AppConfig::instance()->port))
				{
					qCritical("CANNOT connect to Unreal Editor.");
					break;
				}
			}
			else {
				qCritical("Failed to initialize network.");
			}
		} while (false);

		/*HWND hConsole = GetConsoleWindow();
		if (hConsole)
		ShowWindow(hConsole, SW_HIDE);*/

		bool isNoWindow = false;
		if (AppConfig::instance()->cmdline.find("-nw") != std::string::npos)
			isNoWindow = true;

		if (!isNoWindow) {
			AllocConsole();
			freopen("CON", "w", stdout);
		}

		QApplication a(argc, argv);
		UEditorMsgEater msgEater(&a);
		a.installNativeEventFilter(&msgEater);

		TemplateWindow w;
		if (!isNoWindow)
			w.show();
		else
			w.forceRecognize();

		int res = a.exec();

		metaio::IMetaioSDK::shutdownLibrary();

		UninitInsNetwork();

		return res;
	}
	catch (std::exception& e)
	{
		printf("Caught an exception: %s\n", e.what());

		printf("wait 5 seconds to exit ...\n");
		Sleep(5000);

		return -1;
	}
}
